<template>
  <div class="app-container">
    <YearMonthSelector v-model="queryParams.reportingYearMonth" @change="handleYearMonthChange" />

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="楼宇名称" prop="buildingName">
        <el-input
          v-model="queryParams.buildingName"
          placeholder="请输入楼宇名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="楼宇类型" prop="buildingType">
        <el-select v-model="queryParams.buildingType" placeholder="请选择楼宇类型" clearable>
          <el-option
            v-for="dict in building_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入地址"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="建筑结构" prop="constructionStructure">
        <el-input
          v-model="queryParams.constructionStructure"
          placeholder="请输入建筑结构"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="房屋编码" prop="houseCode">
        <el-input
          v-model="queryParams.houseCode"
          placeholder="请输入房屋编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="房屋产权证" prop="propertyCertificate">
        <el-input
          v-model="queryParams.propertyCertificate"
          placeholder="请输入房屋产权证"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="建筑面积" prop="buildingArea">
        <el-input
          v-model="queryParams.buildingArea"
          placeholder="请输入建筑面积"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="租金" prop="rent">
        <el-input
          v-model="queryParams.rent"
          placeholder="请输入租金"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="承租人" prop="tenantName">
        <el-input
          v-model="queryParams.tenantName"
          placeholder="请输入承租人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="contactInfo">
        <el-input
          v-model="queryParams.contactInfo"
          placeholder="请输入联系方式"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="承租人单位" prop="tenantOrganization">
        <el-input
          v-model="queryParams.tenantOrganization"
          placeholder="请输入承租人单位"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出租房类型" prop="rentalType">
        <el-select v-model="queryParams.rentalType" placeholder="请选择出租房类型" clearable>
          <el-option
            v-for="dict in rental_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="间数" prop="roomCount">
        <el-input
          v-model="queryParams.roomCount"
          placeholder="请输入间数"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出租方式" prop="rentalMethod">
        <el-select v-model="queryParams.rentalMethod" placeholder="请选择出租方式" clearable>
          <el-option
            v-for="dict in rental_method"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="reportStatus === '0'">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['report:rental_house:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5" v-if="reportStatus === '0'">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['report:rental_house:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5" v-if="reportStatus === '0'">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['report:rental_house:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['report:rental_house:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5" v-if="reportStatus === '0'">
        <el-button
          type="success"
          plain
          @click="handleReport"
        >立即上报</el-button>
      </el-col>
      <el-col :span="1.5" v-else>
        <el-button
          type="info"
          plain
          disabled
        >已上报</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="rental_houseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="楼宇名称" align="center" prop="buildingName" />
      <el-table-column label="楼宇类型" align="center" prop="buildingType">
        <template #default="scope">
          <dict-tag :options="building_type" :value="scope.row.buildingType"/>
        </template>
      </el-table-column>
      <el-table-column label="地址" align="center" prop="address" />
      <el-table-column label="建筑结构" align="center" prop="constructionStructure" />
      <el-table-column label="房屋编码" align="center" prop="houseCode" />
      <el-table-column label="房屋产权证" align="center" prop="propertyCertificate" />
      <el-table-column label="建筑面积" align="center" prop="buildingArea" />
      <el-table-column label="租金" align="center" prop="rent" />
      <el-table-column label="承租人" align="center" prop="tenantName" />
      <el-table-column label="联系方式" align="center" prop="contactInfo" />
      <el-table-column label="承租人单位" align="center" prop="tenantOrganization" />
      <el-table-column label="出租房类型" align="center" prop="rentalType">
        <template #default="scope">
          <dict-tag :options="rental_type" :value="scope.row.rentalType"/>
        </template>
      </el-table-column>
      <el-table-column label="间数" align="center" prop="roomCount" />
      <el-table-column label="出租方式" align="center" prop="rentalMethod">
        <template #default="scope">
          <dict-tag :options="rental_method" :value="scope.row.rentalMethod"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="reportStatus === '0'">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['report:rental_house:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['report:rental_house:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改出租房对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="rental_houseRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="楼宇名称" prop="buildingName">
          <el-input v-model="form.buildingName" placeholder="请输入楼宇名称" />
        </el-form-item>
        <el-form-item label="楼宇类型" prop="buildingType">
          <el-select v-model="form.buildingType" placeholder="请选择楼宇类型">
            <el-option
              v-for="dict in building_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="建筑结构" prop="constructionStructure">
          <el-input v-model="form.constructionStructure" placeholder="请输入建筑结构" />
        </el-form-item>
        <el-form-item label="房屋编码" prop="houseCode">
          <el-input v-model="form.houseCode" placeholder="请输入房屋编码" />
        </el-form-item>
        <el-form-item label="房屋产权证" prop="propertyCertificate">
          <el-input v-model="form.propertyCertificate" placeholder="请输入房屋产权证" />
        </el-form-item>
        <el-form-item label="建筑面积" prop="buildingArea">
          <el-input v-model="form.buildingArea" placeholder="请输入建筑面积" />
        </el-form-item>
        <el-form-item label="租金" prop="rent">
          <el-input v-model="form.rent" placeholder="请输入租金" />
        </el-form-item>
        <el-form-item label="承租人" prop="tenantName">
          <el-input v-model="form.tenantName" placeholder="请输入承租人" />
        </el-form-item>
        <el-form-item label="联系方式" prop="contactInfo">
          <el-input v-model="form.contactInfo" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="承租人单位" prop="tenantOrganization">
          <el-input v-model="form.tenantOrganization" placeholder="请输入承租人单位" />
        </el-form-item>
        <el-form-item label="出租房类型" prop="rentalType">
          <el-select v-model="form.rentalType" placeholder="请选择出租房类型">
            <el-option
              v-for="dict in rental_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="间数" prop="roomCount">
          <el-input v-model="form.roomCount" placeholder="请输入间数" />
        </el-form-item>
        <el-form-item label="出租方式" prop="rentalMethod">
          <el-select v-model="form.rentalMethod" placeholder="请选择出租方式">
            <el-option
              v-for="dict in rental_method"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Rental_house">
import { listRental_house, getRental_house, delRental_house, addRental_house, updateRental_house } from "@/api/report/rental_house"
import { getMonthlyReportStatusDetail, addReportRecord } from "@/api/report/monthlyReportStatus"
import YearMonthSelector from "@/components/YearMonthSelector/index.vue";

const { proxy } = getCurrentInstance()
const { building_type, rental_method, rental_type } = proxy.useDict('building_type', 'rental_method', 'rental_type')

const rental_houseList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const reportStatus = ref("0") // 默认未上报

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    buildingName: null,
    buildingType: null,
    address: null,
    constructionStructure: null,
    houseCode: null,
    propertyCertificate: null,
    buildingArea: null,
    rent: null,
    tenantName: null,
    contactInfo: null,
    tenantOrganization: null,
    rentalType: null,
    roomCount: null,
    rentalMethod: null,
    reportingYearMonth: null
  },
  rules: {
    buildingName: [
      { required: true, message: "楼宇名称不能为空", trigger: "blur" }
    ],
    buildingType: [
      { required: true, message: "楼宇类型不能为空", trigger: "change" }
    ],
    address: [
      { required: true, message: "地址不能为空", trigger: "blur" }
    ],
    constructionStructure: [
      { required: true, message: "建筑结构不能为空", trigger: "blur" }
    ],
    houseCode: [
      { required: true, message: "房屋编码不能为空", trigger: "blur" }
    ],
    propertyCertificate: [
      { required: true, message: "房屋产权证不能为空", trigger: "blur" }
    ],
    buildingArea: [
      { required: true, message: "建筑面积不能为空", trigger: "blur" }
    ],
    rent: [
      { required: true, message: "租金不能为空", trigger: "blur" }
    ],
    tenantName: [
      { required: true, message: "承租人不能为空", trigger: "blur" }
    ],
    contactInfo: [
      { required: true, message: "联系方式不能为空", trigger: "blur" }
    ],
    tenantOrganization: [
      { required: true, message: "承租人单位不能为空", trigger: "blur" }
    ],
    rentalType: [
      { required: true, message: "出租房类型不能为空", trigger: "change" }
    ],
    roomCount: [
      { required: true, message: "间数不能为空", trigger: "blur" }
    ],
    rentalMethod: [
      { required: true, message: "出租方式不能为空", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询出租房列表 */
function getList() {
  loading.value = true
  // 确保携带 reportingYearMonth 参数
  if (!queryParams.value.reportingYearMonth) {
    const now = new Date()
    queryParams.value.reportingYearMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
  }

  // 获取上报状态
  getReportStatus()

  listRental_house(queryParams.value).then(response => {
    rental_houseList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 获取上报状态
function getReportStatus() {
  const tableName = "rental_house"
  const reportYearMonth = queryParams.value.reportingYearMonth
  if (reportYearMonth) {
    getMonthlyReportStatusDetail(tableName, reportYearMonth).then(response => {
      reportStatus.value = response.data.isReported
    }).catch(() => {
      // 如果获取失败，默认为未上报
      reportStatus.value = "0"
    })
  }
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    buildingName: null,
    buildingType: null,
    address: null,
    constructionStructure: null,
    houseCode: null,
    propertyCertificate: null,
    buildingArea: null,
    rent: null,
    tenantName: null,
    contactInfo: null,
    tenantOrganization: null,
    rentalType: null,
    roomCount: null,
    rentalMethod: null,
    reportingYearMonth: queryParams.value.reportingYearMonth
  }
  proxy.resetForm("rental_houseRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加出租房"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getRental_house(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改出租房"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["rental_houseRef"].validate(valid => {
    if (valid) {
      // 确保传递 reportingYearMonth 字段
      form.value.reportingYearMonth = queryParams.value.reportingYearMonth;
      if (form.value.id != null) {
        updateRental_house(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addRental_house(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除出租房编号为"' + _ids + '"的数据项？').then(function() {
    return delRental_house(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('report/rental_house/export', {
    ...queryParams.value
  }, `rental_house_${new Date().getTime()}.xlsx`)
}

/** 上报按钮操作 */
function handleReport() {
  proxy.$modal.confirm('确定要上报数据吗？上报后数据将不可修改！').then(() => {
    const reportData = {
      tableName: "rental_house",
      reportYearMonth: queryParams.value.reportingYearMonth
    }

    return addReportRecord(reportData)
  }).then(response => {
    if (response.data === 1) {
      proxy.$modal.msgSuccess("上报成功")
      // 更新上报状态为已上报
      reportStatus.value = "1"
    } else {
      proxy.$modal.msgError("上报失败")
    }
  }).catch(error => {
    if (error !== 'cancel') {
      proxy.$modal.msgError("上报失败: " + error.message)
    }
  })
}

// 年月选择变化处理
function handleYearMonthChange() {
  getList()
}

getList()
</script>
